<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\api\model\v1;

use think\Db;
use think\Cache;

/**
 * 微信小程序个人中心模型 
 */
class UserBase extends Base
{
    public $users_id;
    public $session;

    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();

        $token = input('param.token/s');
        if (!empty($token)) {
            $tokenDecode = mchStrCode($token, 'DECODE', '#!@diyminipro#!$');
            if (preg_match_all('/^([0-9a-zA-Z]{8})eyoucms(\d{1,})eyoucms(.+)eyoucms([a-z]{8})eyoucms(.+)eyoucms_token_salt$/i', $tokenDecode, $matches)) {
                $this->users_id = !empty($matches[2][0]) ? intval($matches[2][0]) : 0;
                $openid = !empty($matches[3][0]) ? $matches[3][0] : '';
                $session_key = !empty($matches[5][0]) ? $matches[5][0] : '';
                // 记录缓存, 7天
                $this->session = [
                    'openid' => $openid,
                    'session_key' => $session_key,
                    'users_id' => $this->users_id,
                ];
                Cache::set($token, $this->session, 86400 * 7);
            }
        }

        $queryIng = Cache::get('queryIng') ? 1 : 0;
        if (empty($queryIng)) {
            // 执行开始
            Cache::set('queryIng', 1, 5);
            // 会员订单处理
            if (!empty($this->users_id)) $this->eyou_appletsShopOrderHandle();
        }
        // 执行结束
        Cache::set('queryIng', 0, 86400);
    }

    // 超过指定时间修改为已订单过期，针对未付款订单
    private function eyou_appletsShopOrderHandle()
    {
        // 商家创始人ID
        $where = [
            'parent_id' => 0,
            'role_id' => -1,
        ];
        $adminID = Db::name('admin')->where($where)->getField('admin_id');
        // 超过 未付款自动关闭时间 则修改为已订单过期，仅针对待付款订单
        $this->eyou_paymentOrderHandle($adminID);
        // 超过 发货后自动收货时间 则修改自动确认收货，仅针对待收货订单
        $this->eyou_receivedOrderHandle($adminID);
        // 超过 收货后可维权时间 则修改自动更新为不可维权，仅针对已收货订单
        $this->eyou_receiptOrderHandle();
        // 查询 (赠送积分 && 不可维权) 订单，执行赠送积分
        $this->eyou_consumObtainScoresHandle();
        // 查询 会员已完成且不可维权的订单总金额，计算是否达到自动升级会员级别设定
        $this->eyou_usersAutomaticUpgradeHandle();
    }

    // 超过 未付款自动关闭时间 则修改为已订单过期，仅针对待付款订单
    private function eyou_paymentOrderHandle($adminID = 0)
    {
        // 计算订单过期时间
        $orderUnpayCloseTime = intval($this->usersConfig['order_unpay_close_time']) * 60;
        // 查询过期的订单
        $time = getTime() - intval($orderUnpayCloseTime);
        $where = [
            'order_status' => 0,
            'add_time' => ['<', $time],
            'users_id' => $this->users_id,
        ];
        // 查询订单id数组用于添加订单操作记录
        $shopOrder = Db::name('shop_order')->where($where)->select();
        // $order_ids = !empty($shopOrder) ? $shopOrder : [];
        if (!empty($shopOrder)) {
            $where = [
                'order_id' => ['IN', get_arr_column($shopOrder, 'order_id')]
            ];
            // 还原优惠券
            $useID = Db::name('shop_order')->where($where)->column('use_id');
            if (!empty($useID)) {
                $times = getTime();
                $where = [
                    'use_id' => ['IN', $useID]
                ];
                $couponUse = Db::name('shop_coupon_use')->where($where)->select();
                if (!empty($couponUse)) {
                    foreach ($couponUse as $key => $value) {
                        $where = [
                            'use_id' => $value['use_id'],
                            'users_id' => $this->users_id
                        ];
                        $update = [
                            'use_time' => 0,
                            'update_time' => $times
                        ];
                        if ($value['start_time'] <= $times && $value['end_time'] >= $times) {
                            $update['use_status'] = 0;
                        } else {
                            $update['use_status'] = 2;
                        }
                        Db::name('shop_coupon_use')->where($where)->update($update);
                    }
                }
            }

            // 扣除用于订单支付的积分和余额
            $shopOrderPay = model('v1.ShopOrderPay');
            foreach ($shopOrder as $value) {
                $shopOrderPay->handleOrderBalanceScorePay($value, 'restore');
            }

            // 商品库存恢复
            $orderStock = $shopOrder;
            foreach ($orderStock as $key => $value) {
                // 如果订单是付款减库存则去除，订单过期不恢复库存
                if (isset($value['order_stock_type']) && 1 === intval($value['order_stock_type'])) unset($orderStock[$key]);
            }
            model('v1.ShopGoods')->goodsStockRestore($orderStock, $this->users_id);

            // 批量修改订单状态
            $where = [
                'order_id' => ['IN', get_arr_column($shopOrder, 'order_id')]
            ];
            $update = [
                'order_status' => 4,
                'update_time' => getTime(),
            ];
            Db::name('shop_order')->where($where)->update($update);

            // 添加订单操作记录
            AddOrderAction($shopOrder, 0, $adminID, 4, 0, 0, '订单过期！', '订单超时'.$this->usersConfig['order_unpay_close_time'].'分钟未支付，系统自动关闭！');
        }
    }

    // 超过 发货后自动收货时间 则修改自动确认收货，仅针对待收货订单
    private function eyou_receivedOrderHandle($adminID = 0)
    {
        // 计算订单自动收货时间
        $orderAutoReceiptTime = intval($this->usersConfig['order_auto_receipt_time']) * 86400;
        // 查询待收货订单
        $time = getTime() - intval($orderAutoReceiptTime);
        $where = [
            'order_status' => 2,
            'users_id' => $this->users_id,
            'express_time' => ['<', $time],
        ];
        // 查询订单id数组用于添加订单操作记录
        $order_ids = Db::name('shop_order')->field('order_id')->where($where)->select();
        if (!empty($order_ids)) {
            // 批量修改订单状态
            $update = [
                'order_status' => 3,
                'update_time' => getTime(),
                'confirm_time' => getTime(),
            ];
            Db::name('shop_order')->where($where)->update($update);

            // 添加订单操作记录
            AddOrderAction($order_ids, 0, $adminID, 4, 0, 0, '订单过期！', '订单超时'.$this->usersConfig['order_auto_receipt_time'].'天未确认收货，系统自动确认！');
        }
    }

    // 超过 收货后可维权时间 则修改自动更新为不可维权，仅针对已收货订单
    private function eyou_receiptOrderHandle()
    {
        // 计算订单可维权时间
        $orderRightProtectTime = intval($this->usersConfig['order_right_protect_time']) * 86400;
        // 查询待收货订单
        $time = getTime() - intval($orderRightProtectTime);
        $where = [
            'order_status' => 3,
            'order_is_service' => 0,
            'users_id' => $this->users_id,
            'confirm_time' => ['<', $time],
        ];
        // 查询订单id数组用于添加订单操作记录
        $order_ids = Db::name('shop_order')->field('order_id')->where($where)->select();
        if (!empty($order_ids)) {
            // 批量修改订单状态
            $update = [
                'order_is_service' => 1,
                'update_time' => getTime(),
            ];
            Db::name('shop_order')->where($where)->update($update);
        }
    }

    // 查询 (赠送积分 && 不可维权) 订单，执行赠送积分
    private function eyou_consumObtainScoresHandle()
    {
        // 查询订单
        $where = [
            'order_status' => 3,
            'order_is_service' => 1,
            'is_obtain_scores' => 0,
            'obtain_scores' => ['>', 0],
            'users_id' => $this->users_id,
        ];
        // 查询订单id数组用于添加订单操作记录
        $shopOrder = Db::name('shop_order')->where($where)->select();
        if (!empty($shopOrder)) {
            // 赠送会员积分
            foreach ($shopOrder as $key => $value) {
                $insert = [
                    'type' => 8,
                    'users_id' => $value['users_id'],
                    'score' => $value['obtain_scores'],
                    'info' => '商城消费赠送积分',
                    'remark' => '商城消费赠送积分',
                ];
                eyou_give_score($insert, 2, true);
            }

            // 批量修改订单状态
            $update = [
                'is_obtain_scores' => 1,
                'update_time' => getTime(),
            ];
            Db::name('shop_order')->where($where)->update($update);
        }
    }

    // 查询 会员已完成且不可维权的订单总金额，计算是否达到自动升级会员级别设定
    private function eyou_usersAutomaticUpgradeHandle()
    {
        // 查询会员当前等级折扣率
        $where = [
            'a.users_id' => $this->users_id
        ];
        $discount = Db::name('users')->alias('a')->join('__USERS_LEVEL__ b', 'a.level = b.level_id', 'LEFT')->where($where)->getField('b.discount');
        // 查询会员等级最低折扣率
        $usersLevel = Db::name('users_level')->order('discount asc')->find();
        // 判断当前是否需要升级
        if (intval($discount) > intval($usersLevel['discount'])) {
            // 查询是否达到升级需求
            $where = [
                'order_status' => 3,
                'order_is_service' => 1,
                'users_id' => $this->users_id,
            ];
            $field = 'order_id, (pay_use_cash + pay_use_balance) as totalNum';
            $shopOrder = Db::name('shop_order')->where($where)->field($field)->getAllWithIndex('order_id');
            $upgradeVal = !empty($usersLevel['upgrade_val']) ? intval($usersLevel['upgrade_val']) : 0;
            if (!empty($shopOrder) && 1 === intval($usersLevel['upgrade'])) {
                // 累计订单金额
                $totalOrderPrice = 0;
                foreach ($shopOrder as $value) {
                    $totalOrderPrice = floatval($totalOrderPrice) + floatval($value['totalNum']);
                }
                $order_ids = !empty($shopOrder) ? get_arr_column($shopOrder, 'order_id') : [];
                if (!empty($order_ids)) {
                    $where = [
                        'status' => 7,
                        'order_id' => ['IN', $order_ids]
                    ];
                    $actualPrice = Db::name('shop_order_service')->where($where)->sum('actual_price');
                    // 扣除已维权完成的金额
                    $totalOrderPrice = floatval($totalOrderPrice) - floatval($actualPrice);
                }
                // 是否满足升级条件
                if (floatval($totalOrderPrice) >= floatval($upgradeVal)) {
                    $where = [
                        'users_id' => $this->users_id
                    ];
                    $update = [
                        'level' => $usersLevel['level_id'],
                        'update_time' => getTime(),
                    ];
                    Db::name('users')->where($where)->update($update);
                }
            } else if (!empty($shopOrder) && 2 === intval($usersLevel['upgrade'])) {
                // 订单总数量
                $totalOrderNum = !empty($shopOrder) ? count($shopOrder) : 0;
                // 是否满足升级条件
                if (floatval($totalOrderNum) >= floatval($upgradeVal)) {
                    $where = [
                        'users_id' => $this->users_id
                    ];
                    $update = [
                        'level' => $usersLevel['level_id'],
                        'update_time' => getTime(),
                    ];
                    Db::name('users')->where($where)->update($update);
                }
            }
        }
    }

}